package com.sogoodsoft.web.common;

import java.util.ArrayList;
import java.util.List;

import org.springside.modules.utils.web.struts2.Struts2Utils;

import com.opensymphony.xwork2.ActionSupport;
import com.sogoodsoft.util.Computer;

public class ComputeAction extends ActionSupport {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private String action;

    private String val, vals[], result;

    @Override
    public String execute() throws Exception {
        if (val != null && val.length() > 0) {
            vals = val.split(",");
        }

        // 相加后，四舍五入
        if ("roundAdd".equals(action)) {
            result = Computer.roundAdd(vals);
        }
        // 相乘后，四舍五入
        if ("roundMutiply".equals(action)) {
            result = Computer.roundMutiply(vals);
        }

        if ("orderForm".equals(action)) {
            result = orderCompute(vals);
        }

        // 输出结果 文本格式的数字
        Struts2Utils.getResponse().getWriter().print(result);
        return null;
    }

    /**
     * 订单计算，数量,单价对，
     * 
     * @param vals
     * @return 金额小计、总金额，逗号分隔
     */
    public String orderCompute(String... vals) {
        List < String > list = new ArrayList < String >();

        // 小计
        String one = "0";

        // 合计
        String total = "0";

        for (int i = 0; i < vals.length; i += 2) {
            one = Computer.mutiply(vals[i], vals[i + 1]);

            // 计算合计，不舍入
            total = Computer.add(total, one);

            // 四舍五入小计
            one = Computer.round(one);
            list.add(one);
        }

        // 最终合计舍入
        total = Computer.round(total);
        list.add(total);

        // 逗号字符串
        StringBuffer result = new StringBuffer();
        for (String v : list) {
            result.append(",");
            result.append(v);
        }
        return result.substring(1);
    }

    public String getAction() {
        return action;
    }

    public void setAction(String action) {
        this.action = action;
    }

    public String getVal() {
        return val;
    }

    public void setVal(String val) {
        this.val = val;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

}
